# usr/bin/env python3
import threading
from datetime import datetime

import serial
import time

# Receive_serial = serial.Serial('com16', baudrate=115200)
import serial
import struct

FRAME_HEADER = 0x0606  # 2字节帧头
FRAME_HEADER = struct.pack('!H', FRAME_HEADER)
FRAME_TAIL = 0x66AA  # 2字节帧尾
FRAME_TAIL = struct.pack('!H', FRAME_TAIL)


def calculate_checksum(data):
    return sum(data) % 256  # 简单的校验和


def get_time(timestamp, reserved):
    current_utc_time = datetime.utcnow()
    # 获取年、月、日、时、分、秒和毫秒
    year = current_utc_time.year
    year = int(str(year)[-2::]) - timestamp[0]
    month = current_utc_time.month - timestamp[1]
    day = current_utc_time.day - timestamp[2]
    hour = current_utc_time.hour - timestamp[3]
    minute = current_utc_time.minute - timestamp[4]
    second = current_utc_time.second - timestamp[5]
    millisecond = round(current_utc_time.microsecond / 1000) - timestamp[6]
    a = struct.unpack('!H', reserved)[0] * 100
    reserved = second * 1000 + round(millisecond) - a
    # print(second*1000)
    # print(round(millisecond/10))
    # print(a)
    # reserved=struct.unpack('!H', reserved)[0]*1000
    #    millisecond=millisecond-reserved
    # print(year,month,day,hour,minute,second,millisecond)
    # print(timestamp)

    return (year, month, day, hour, minute, second, millisecond, reserved, a)


def receive_frame(serial_port):
    while True:
        # 读取帧头
        header = serial_port.read(2)
        # header=b'\x06\x06\x1c\x18\x07\x0c\x04/\x17 \x8b\x01\x02\x03\x04\x01\x02\x03\x04\x05\x06\x07\x08\x00\x00jf\xaa'
        if header:
            # print(header)
            if header == FRAME_HEADER:
                # 读取长度
                # length = struct.unpack('!B', serial_port.read(1))[0]
                length = serial_port.read(1)
                # timestamp
                # timestamp=struct.unpack('!BBBBBBH',serial_port.read(8))
                timestamp = serial_port.read(8)

                # 读取命令
                # command = struct.unpack('!I', serial_port.read(4))
                command = serial_port.read(4)
                # 读取数据

                # control_param = struct.unpack('!Q', serial_port.read(8))
                control_param = serial_port.read(8)
                # reserved = struct.unpack('!H', serial_port.read(2))
                reserved = serial_port.read(2)
                # 读取校验和
                checksum = struct.unpack('!B', serial_port.read(1))[0]
                # 读取帧尾
                # tail = struct.unpack('!H', serial_port.read(2))
                tail = serial_port.read(2)

                if tail == FRAME_TAIL and checksum == calculate_checksum(
                        length + timestamp + command + control_param + reserved):
                    timestamp = struct.unpack('!BBBBBBH', timestamp)
                    time_interval = get_time(timestamp, reserved)
                    return timestamp, command, control_param, time_interval
                else:
                    print("校验失败或帧尾错误")
            elif header == b'\x00\x01':
                length = serial_port.read(5)
                # print(length)
                # print(length[1]==255)
                if length[1] == 255 and length[3] == 255:
                    # print(length[2]-256)
                    env_rssi = length[2] - 256
                    data = length[4] - 256
                    print(f'env_rssi: {env_rssi},data_rssi: {data}')
                    print()
            else:
                print("帧头错误")
    else:
        ser.close()


def get_rssi(ser):
    while 1:
        ser.write(b'\x00\x01\x01')
        time.sleep(1)


# 示例用法
port = 'COM9'
baud_rate = 115200

with serial.Serial(port, baud_rate, timeout=0.5) as ser:
    th1 = threading.Thread(target=get_rssi, args=(ser,))
    th1.start()
    while 1:
        timestamp, command, control_param, time_interval = receive_frame(ser)
        print()
        print("接收到的命令:", command)
        # print("接收到的时间戳:", timestamp)
        # print(f'diff: {time_interval[:-1]},diff_time: {time_interval[-2]},interval: {time_interval[-1]}')
        print(f'diff_time: {time_interval[-2]},interval: {time_interval[-1]}')

        # print("接收到的随机数据:", control_param)